package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.utils.*;
import com.example.lotterysystem.service.IVerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/1/27
 */
@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {

    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L;
    private static final String VERIFICATION_CODE_TEMPLATE_CODE = "SMS_478520502";

    private static String TITLE = "验证码";


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private MailUtil mailUtil;

    /**
     * 发送验证码
     *
     * @param mail
     */
    @Override
    public void sendVerificationCode(String mail) {
        //校验邮箱
        if (!RegexUtil.checkMail(mail)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        //生成验证码
        String captcha = CaptchaUtil.getCaptcha(4);
        String context = constructContext(captcha);
        //发送验证码
        mailUtil.sendSampleMail(mail, TITLE, context);
        //缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX + mail, captcha, VERIFICATION_CODE_TIMEOUT);
    }

    /**
     * 从 Redis 中获取验证码
     *
     * @param mail
     * @return
     */
    @Override
    public String getVerificationCode(String mail) {
        //校验手机号
        if (!RegexUtil.checkMail(mail)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_USED);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX + mail);
    }

    private String constructContext(String captcha) {
        return "您本次验证码为" + captcha + "，请在一分钟内进行验证。";
    }
}
